const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const fs = require('fs');
const rfs = require('rotating-file-stream');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const logUtil = require('./untils/logUtil');
const app = express();

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'favicon.ico')));

// 初始化错误日志目录
logUtil.initPath();

//记录请求日志
const logDirectory = path.join(__dirname, 'logs');

// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

// create a rotating write stream
const accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: logDirectory
});
// setup the logger
app.use(logger('combined', {stream: accessLogStream}));

//链接数据库

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const index = require('./routes/index');
const users = require('./routes/users');
app.use('/api/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    logUtil.error(err,req);
    res.status(err.status || 500);
    /*res.render('error', {
        message: err.message,
        error: {}
    });*/
    res.json({code:500,msg:'Internal server error'});
});

module.exports = app;
